package com.bidevalution.controller.api;

import com.bidevalution.business.context.AreaEnum;
import com.bidevalution.business.service.BidCaseStatService;
import com.bidevalution.dao.entity.SectionInfoResult;
import com.qtp.base.models.ExcelMsg;
import com.qtp.common.core.excel.ExcelWriter;
import com.qtp.core.model.Paging;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.GsonUtil;
import com.qtp.core.util.OConvertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@RestController
@Api(tags = "开评标情况统计")
@RequestMapping("/bidCaseStat")
public class BidCaseStatController extends BaseController{

    @Value("${areaCodes}")
    private String AREA_CODES;

    @Autowired
    BidCaseStatService bidCaseStatService;

    @ApiOperation(value = "查询项目信息", notes = "查询项目信息", response = SectionInfoResult.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "area", value = "地区", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionName", value = "标段名称(支持模糊查找)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间,格式:[yyyy-MM-dd]", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间,格式:[yyyy-MM-dd]", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startIndex", value = "从第几条开始(为空不分页)", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "查询几条(为空不分页)", dataType = "int", paramType = "query")
    })
    @PostMapping("/getSectionPaging")
    public Response<Paging<SectionInfoResult>> getSectionPaging(@RequestParam(name = "area", required = false) String area,
                                                                @RequestParam(name = "sectionName", required = false) String sectionName,
                                                                @RequestParam(name = "startTime", required = false) String startTime,
                                                                @RequestParam(name = "endTime", required = false) String endTime,
                                                                @RequestParam(name = "startIndex", required = false, defaultValue = "0") int startIndex,
                                                                @RequestParam(name = "pageSize", required = false, defaultValue = "0") int pageSize) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("area", area);
            params.put("sectionName", specialCharFormatToMysql(sectionName));
            params.put("startTime", OConvertUtils.isEmpty(startTime) ? null : startTime);
            params.put("endTime", OConvertUtils.isEmpty(endTime) ? null : endTime);
            params.put("startIndex", startIndex);
            params.put("pageSize", pageSize);
            return Response.ok(bidCaseStatService.getSectionPaging(params));
        } catch (Exception e) {
            return Response.fail(GsonUtil.toJsonWithGson(e));
        }
    }

    @ApiOperation(value = "投标单位明细", notes = "投标单位明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionCode", value = "标段编码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "entName", value = "单位名称", required = false,dataType = "String", paramType = "query"),
    })
    @PostMapping("/getBiddersDetails")
    public Response getBiddersDetails(@RequestParam(name = "sectionCode") String sectionCode
            ,@RequestParam(name = "entName", required = false) String entName) {
        try {
            if (OConvertUtils.isEmpty(sectionCode)) {
                return Response.fail("sectionCode：标段编码不可为空");
            }
            Map<String, Object> params = new HashMap<String, Object>(2);
            params.put("sectionCode", sectionCode);
            if(StringUtils.isNotBlank(entName)) {
                params.put("entName", "%" + entName + "%");
            }
            List<Map<String, Object>> bidUnitList = bidCaseStatService.getBidUnitList(params);
            Map<String, Object> bidFileBrandStat = bidCaseStatService.getBidFileBrandStat(params);
            bidFileBrandStat.put("bidUnitList", bidUnitList);
            int qzrj = OConvertUtils.getInt(bidFileBrandStat.get("qzrj"));
            int gtxd = OConvertUtils.getInt(bidFileBrandStat.get("gtxd"));
            int hzpm = OConvertUtils.getInt(bidFileBrandStat.get("hzpm"));
            bidFileBrandStat.put("bidUnitTotal", qzrj + gtxd + hzpm);
            return Response.ok(bidFileBrandStat);
        } catch (Exception e) {
            return Response.fail(GsonUtil.toJsonWithGson(e));
        }
    }

    @ApiOperation(value = "获取地区", notes = "获取地区")
    @GetMapping("/getAreas")
    public Response getAreas() {
        try {
            if (OConvertUtils.isEmpty(AREA_CODES)) {
                return Response.fail("未配置地区参数！");
            }
            String[] areaCodes = AREA_CODES.split(",");
            if (areaCodes != null && areaCodes.length != 0) {
                Map<String, Object> areaMap = new HashMap<String, Object>();
                for (String item : areaCodes) {
                    item = item.trim();
                    AreaEnum areaEnum = AreaEnum.getByCode(item);
                    if (areaEnum != null) {
                        areaMap.put(areaEnum.getCode(), areaEnum.getName());
                    }
                }
                return Response.ok(areaMap);
            } else {
                return Response.fail("地区参数配置错误！");
            }
        } catch (Exception e) {
            log.error("LOG[]getAreas[]{},error={},params={}", "获取地区异常", GsonUtil.toJsonWithGson(e));
            return Response.fail(GsonUtil.toJsonWithGson(e));
        }
    }

    @ApiOperation(value = "导出投标明细", notes = "导出投标明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "areaCode", value = "地区编码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionName", value = "标段名称(支持模糊查找)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开标时间开始时间,格式:[yyyy-MM-dd]", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "开标时间结束时间,格式:[yyyy-MM-dd]", dataType = "String", paramType = "query")
    })
    @GetMapping("/exportBiddersDetails")
    public ExcelMsg exportBiddersDetails(@RequestParam(name = "areaCode") String areaCode, @RequestParam(name = "sectionName", required = false) String sectionName, @RequestParam(name = "startTime", required = false) String startTime, @RequestParam(name = "endTime", required = false) String endTime, HttpServletResponse response) {
        try {
            AreaEnum areaEnum = AreaEnum.getByCode(areaCode);
            if (OConvertUtils.isEmpty(areaCode) || areaEnum == null) {
                return ExcelMsg.fail("areaCode：地区编码不可为空");
            }
            if (AREA_CODES.indexOf(areaCode) != -1) {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("areaName", areaEnum.getName());
                params.put("areaCode", areaEnum.getCode());
                params.put("startTime", OConvertUtils.isEmpty(startTime) ? null : startTime);
                params.put("endTime", OConvertUtils.isEmpty(endTime) ? null : endTime);
                params.put("sectionName", specialCharFormatToMysql(sectionName));
                List<Map<String, Object>> areaProjectBidDetail = bidCaseStatService.getAreaProjectBidDetail(params);
                if (!areaProjectBidDetail.isEmpty()) {
                    //列表表头
                    Map<String, String> headMap = new LinkedHashMap<>();
                    headMap.put("section_code", "工程编号");
                    headMap.put("section_name", "工程名称");
                    headMap.put("evaluationBidSide", "评标方法");
                    headMap.put("total", "有效投标单位家数");
                    headMap.put("qzrj", "擎洲");
                    headMap.put("hzpm", "品茗");
                    headMap.put("gtxd", "国泰");
                    String currentDateStr = DateUtil.getCurrentDateStr(DateUtil.PT3);
                    String title = OConvertUtils.isEmpty(startTime)
                            ? OConvertUtils.isEmpty(endTime) ? String.format("【%s】截止%s开标项目统计信息", areaEnum.getName(), currentDateStr) : String.format("【%s】%s至%s开标项目统计信息", areaEnum.getName(), currentDateStr, endTime)
                            : OConvertUtils.isEmpty(endTime) ? String.format("【%s】%s至%s开标项目统计信息", areaEnum.getName(), startTime, currentDateStr) : String.format("【%s】%s至%s开标项目统计信息", areaEnum.getName(), startTime, endTime);
                    ExcelWriter.downloadExcelFile(title, headMap, areaProjectBidDetail, response);
                    return ExcelMsg.ok();
                } else {
                    return ExcelMsg.fail("该地区下没有数据！");
                }
            } else {
                return ExcelMsg.fail("地区编码不存在");
            }
        } catch (Exception e) {
            return ExcelMsg.fail(GsonUtil.toJsonWithGson(e));
        }
    }

    @ApiOperation(value = "评审区间导出", notes = "评审区间导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sectionId", value = "标段id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sectionStepId", value = "环境id", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/exportPingShenQuJianData")
    public ExcelMsg exportPingShenQuJianData(HttpServletResponse response, @RequestParam(name = "sectionId") String sectionId, @RequestParam(name = "sectionStepId") String sectionStepId) {
        try {
            if (OConvertUtils.isEmpty(sectionId) || OConvertUtils.isEmpty(sectionStepId)) {
                return ExcelMsg.fail("参数错误！");
            }
            //列表表头
            Map<String, String> headMap = new LinkedHashMap<>();
            headMap.put("row_num", "序号");
            headMap.put("tbdw", "投标单位");
            headMap.put("tbbj", "投标报价（元）");
            ExcelWriter.downloadExcelFile("通过资格审查的投标单位信息", headMap, bidCaseStatService.getExportPingShenQuJianData(sectionId,sectionStepId), response);
            return ExcelMsg.ok();
        } catch (Exception e) {
            log.error("LOG[]exportPingShenQuJianData[]{},error={},params={}","评审区间导出异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(response)+";"+GsonUtil.toJsonWithGson(sectionId)+";"+GsonUtil.toJsonWithGson(sectionStepId));
            return ExcelMsg.fail("导出失败！");
        }
    }

    @ApiOperation(value = "导出投标单位的附件pdf", notes = "导出投标单位的附件pdf")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "entIds", value = "投标单位id", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/exportEntPdf")
    public void exportEntPdf(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "entIds") String entIds) throws Exception {
        try {
            bidCaseStatService.exportEntPdf(entIds, request, response);
        } catch(Exception e) {
            log.error("导出投标单位pdf出错", e);
            throw e;
        }
    }
}
